package com.assignwork.service.impl;

import com.assignwork.dto.AssignWorkDTO;
import com.assignwork.dto.LineAuditDTO;
import com.assignwork.dto.WorkArrangeLandSearchDTO;
import com.assignwork.dto.WorkArrangeLandSubmitDTO;
import com.assignwork.entity.WorkArrangeFixedMachine;
import com.assignwork.entity.WorkArrangeLand;
import com.assignwork.entity.WorkArrangeMachines;
import com.assignwork.entity.WorkArrangeWorkers;
import com.assignwork.mapper.WorkArrangeLandMapper;
import com.assignwork.service.*;
import com.assignwork.vo.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.common.cache.AreaSettingsCache;
import lombok.AllArgsConstructor;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.system.cache.DictBizCache;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.dc.pr.PRError;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName WorkArrangeLandServiceImpl
 * @Description 陆运配工接口实现
 * @Author dujianyu
 * @Date 2023/12/18 8:51
 */
@Service
@AllArgsConstructor
public class WorkArrangeLandServiceImpl extends BaseServiceImpl<WorkArrangeLandMapper, WorkArrangeLand> implements IWorkArrangeLandService {

    private static final String ARRANGE_TYPE = "LAND";
    private IWorkArrangeWorkersService workersService;
    private IWorkArrangeMachinesService machinesService;
    private IWorkArrangeFixedMachineService fixedMachineService;
    private ILineNoService lineNoService;
    private IWorkArrangeAreasService areasService;
    private IAssignWorkService assignWorkService;

    @Override
    public boolean submitWaLand(WorkArrangeLandSubmitDTO dto) {
        if (Func.isNull(dto.getId())) {
            dto.setWorkNo(lineNoService.getNewLineNo(dto.getPlanDate()));
        }
        WorkArrangeLand entity = BeanUtil.copy(dto, WorkArrangeLand.class);
        super.saveOrUpdate(entity);
        if (entity != null) {
            return workersService.submitWaWorkers(entity.getId(), dto.getWorkers(), ARRANGE_TYPE)
                    && machinesService.submitWaMachines(entity.getId(),dto.getMachines(), ARRANGE_TYPE)
                    && fixedMachineService.submitWaFixedMachine(entity.getId(), dto.getFixedMachines(), ARRANGE_TYPE)
                    && areasService.submitWaAreas(entity.getId(), dto.getAreas(), ARRANGE_TYPE);
        }
        return true;
    }

    @Override
    public WorkArrangeLandPageVO selectWaLandPage(WorkArrangeLandSearchDTO dto, IPage<WorkArrangeLandListVO> page) {
        List<WorkArrangeLandListVO> data = baseMapper.selectWaLandList(dto, page);
        WorkArrangeLandPageVO res = new WorkArrangeLandPageVO();
        Integer fmKinds = 0;
        if (!Func.isEmpty(data)) {
            fmKinds = fixedMachineService.fixedMachineKindsByarrangeIds(data.stream().map(WorkArrangeLandListVO::getId).collect(Collectors.toList()));
        }
        res.setFixedMachineKinds(fmKinds);
        res.setWalPage(page.setRecords(dataProcess(data)));
        return res;
    }

    @Override
    public boolean removeWaLand(Long id) {
        return super.deleteLogic(Func.toLongList(id.toString()))
                && workersService.removeByArrangeId(id)
                && machinesService.removeByArrangeId(id)
                && fixedMachineService.removeByArrangeId(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean importFromPrevious(WorkArrangeLandSearchDTO dto) {
        QueryWrapper<WorkArrangeLand> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(WorkArrangeLand::getPlanDate, dto.getPlanDate().minusDays(1))
                .eq(WorkArrangeLand::getIsDeleted, 0);
        List<WorkArrangeLand> previousList = baseMapper.selectList(queryWrapper);
        if (Func.isEmpty(previousList)) {
            throw new RuntimeException("之前一天无配工数据");
        }
        for (WorkArrangeLand preData : previousList) {
            WorkArrangeLand newData = new WorkArrangeLand();
            newData.setArea(preData.getArea());
            newData.setLandWorkType(preData.getLandWorkType());
            newData.setWorkNo(lineNoService.getNewLineNo(dto.getPlanDate()));
            newData.setCargoType(preData.getCargoType());
            newData.setCraneInfo(preData.getCraneInfo());
            newData.setExcavatorInfo(preData.getExcavatorInfo());
            newData.setForkliftInfo(preData.getForkliftInfo());
            newData.setLoaderInfo(preData.getLoaderInfo());
            newData.setTimeSpace(preData.getTimeSpace());
            newData.setPlanDate(dto.getPlanDate());
            newData.setLoadType(preData.getLoadType());
            newData.setPackageBulk(preData.getPackageBulk());
            newData.setShipName(preData.getShipName());
            newData.setRemark(preData.getRemark());
            newData.setWorkerInfo(preData.getWorkerInfo());
            newData.setFixedMachineInfo(preData.getFixedMachineInfo());

            if (!super.saveOrUpdate(newData)) {
                throw new RuntimeException("新增失败");
            }

            List<WorkArrangeWorkersVO> preWorkers = workersService.infoByArrangeId(preData.getId());
            if (!Func.isEmpty(preWorkers)) {
                List<WorkArrangeWorkers> newWorkers = new ArrayList<>();
                for (WorkArrangeWorkersVO preWorkerData : preWorkers) {
                    WorkArrangeWorkers newWorker = new WorkArrangeWorkers();
                    newWorker.setArrangeId(newData.getId());
                    newWorker.setArrangeType("LAND");
                    newWorker.setTeamId(preWorkerData.getTeamId());
                    newWorker.setWorkers(preWorkerData.getWorkers());
                    newWorkers.add(newWorker);
                }
                if (!workersService.saveOrUpdateBatch(newWorkers)) {
                    throw new RuntimeException("新增工人信息失败");
                }
            }

            List<WorkArrangeFixedMachineVO> preFixedMachines = fixedMachineService.infoByArrangeId(preData.getId());
            if (!Func.isEmpty(preFixedMachines)) {
                List<WorkArrangeFixedMachine> newFixedMachines = new ArrayList<>();
                for (WorkArrangeFixedMachineVO preFixedMachineData : preFixedMachines) {
                    WorkArrangeFixedMachine newFixedMachine = new WorkArrangeFixedMachine();
                    newFixedMachine.setArrangeId(newData.getId());
                    newFixedMachine.setArrangeType("LAND");
                    newFixedMachine.setFixedMachineId(preFixedMachineData.getFixedMachineId());
                    newFixedMachines.add(newFixedMachine);
                }
                if (!fixedMachineService.saveOrUpdateBatch(newFixedMachines)) {
                    throw new RuntimeException("新增固机信息失败");
                }
            }

            List<WorkArrangeMachinesVO> preMachines = machinesService.infoByArrangeId(preData.getId());
            if (!Func.isEmpty(preMachines)) {
                List<WorkArrangeMachines> newMachines = new ArrayList<>();
                for (WorkArrangeMachinesVO preMachineData : preMachines) {
                    WorkArrangeMachines newMachineData = new WorkArrangeMachines();
                    newMachineData.setArrangeId(newData.getId());
                    newMachineData.setArrangeType("LAND");
                    newMachineData.setMachineKind(preMachineData.getMachineKind());
                    newMachineData.setTeamId(preMachineData.getTeamId());
                    newMachineData.setMachines(preMachineData.getMachines());
                    newMachines.add(newMachineData);
                }
                if (!machinesService.saveOrUpdateBatch(newMachines)) {
                    throw new RuntimeException("新增流机信息失败");
                }
            }
        }
        return true;
    }

    @Override
    public IPage<WorkArrangeLandVO> pageWorkArrangeLand(BladeUser bladeUser, IPage<WorkArrangeLandVO> page, AssignWorkDTO dto) {
        IPage<WorkArrangeLandVO> res = this.baseMapper.pageWorkArrangeLand(page, dto);
        for (WorkArrangeLandVO item : res.getRecords()) {
            item.setLandWorkTypeName(DictBizCache.getValue("land_work_type", item.getLandWorkType()));
            item.setLoadTypeName(DictBizCache.getValue("load_type", item.getLoadType()));
            item.setPackageBulkName(DictBizCache.getValue("package_bulk", item.getPackageBulk()));
            item.setTimeSpaceName(DictBizCache.getValue("time_space", item.getTimeSpace()));
//            item.setAreaName(AreaSettingsCache.getValue(item.getArea()));

            for (WorkArrangeMachinesVO vo : item.getListFlowMachine()) {
                vo.setMachineKindName(DictBizCache.getValue("machine_kind", vo.getMachineKind()));
            }

            for (WorkArrangeFixedMachineVO vo : item.getListFixedMachine()) {
                vo.setFixedMachinePositionName(DictBizCache.getValue("machine_position", vo.getFixedMachinePosition()));
            }

        }

        return res;
    }

    @Override
    public List<WorkArrangeLandMobileVO> listLandWorkArrangeMobile(IPage page, LineAuditDTO dto) {
        List<WorkArrangeLandMobileVO> res = baseMapper.listLandWorkArrangeMobile(page, dto);
        for (WorkArrangeLandMobileVO item : res) {
            item.setLandWorkTypeName(DictBizCache.getValue("land_work_type", item.getLandWorkType()));
            item.setLoadTypeName(DictBizCache.getValue("load_type", item.getLoadType()));
            item.setPackageBulkName(DictBizCache.getValue("package_bulk", item.getPackageBulk()));
            item.setTimeSpaceName(DictBizCache.getValue("time_space", item.getTimeSpace()));
        }
        return res;
    }

    @Override
    public WorkArrangeLandInfoVO arrangeInfoLandByArrangeId(Long arrangeId) {
        WorkArrangeLandInfoVO vo = baseMapper.arrangeInfoLandByArrangeId(arrangeId);
        if (vo == null) {
            return new WorkArrangeLandInfoVO();
        }
        vo.setLandWorkTypeName(DictBizCache.getValue("land_work_type", vo.getLandWorkType()));
        vo.setLoadTypeName(DictBizCache.getValue("load_type", vo.getLoadType()));
        vo.setPackageBulkName(DictBizCache.getValue("package_bulk", vo.getPackageBulk()));
        vo.setTimeSpaceName(DictBizCache.getValue("time_space", vo.getTimeSpace()));

        List<AssignWorkVO> assignWorkVOS = assignWorkService.listAssignWorkByArrangeId(arrangeId);
        List<AssignWorkVO> collect = assignWorkVOS.stream().filter(AssignWorkVO::isLoader).collect(Collectors.toList());

        if (Func.isNotEmpty(collect)) {
            vo.setAssignWork(collect.get(0));
        }

        return vo;
    }

    private List<WorkArrangeLandListVO> dataProcess(List<WorkArrangeLandListVO> data) {
        for (WorkArrangeLandListVO item : data) {
            item.setLandWorkTypeName(DictBizCache.getValue("land_work_type", item.getLandWorkType()));
            item.setLoadTypeName(DictBizCache.getValue("load_type", item.getLoadType()));
            item.setPackageBulkName(DictBizCache.getValue("package_bulk", item.getPackageBulk()));
            item.setTimeSpaceName(DictBizCache.getValue("time_space", item.getTimeSpace()));
        }
        return data;
    }
}
